<template>
  <div class="seckill-product-management">
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">新增秒杀商品</el-button>
    </div>

    <el-table :data="tableData" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="商品名称" width="150" />
      <el-table-column prop="description" label="商品描述" width="200" />
      <el-table-column prop="image" label="商品图片" width="100">
        <template #default="{ row }">
          <el-image 
            v-if="row.image"
            :src="row.image" 
            :preview-src-list="[row.image]" 
            fit="cover" 
            class="product-image"
          />
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="originalPrice" label="原价" width="100">
        <template #default="{ row }">
          ¥{{ row.originalPrice }}
        </template>
      </el-table-column>
      <el-table-column prop="price" label="秒杀价" width="100">
        <template #default="{ row }">
          ¥{{ row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="80" />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间" width="180" />
      <el-table-column prop="updatedTime" label="更新时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button 
            :type="row.status === 1 ? 'warning' : 'success'" 
            link 
            @click="handleStatusChange(row)"
          >
            {{ row.status === 1 ? '下架' : '上架' }}
          </el-button>
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isAdd ? '新增秒杀商品' : '编辑秒杀商品'"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="padding: 0 20px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        <el-form-item label="商品图片" prop="image">
          <el-upload
            class="avatar-uploader"
            :action="null"
            :show-file-list="false"
            :http-request="handleImageUpload"
            :before-upload="beforeImageUpload"
          >
            <img v-if="form.image" :src="form.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">支持 jpg、png 格式，大小不超过 2MB</div>
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <el-input-number
            v-model="form.originalPrice"
            :precision="2"
            :step="0.1"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="秒杀价" prop="price">
          <el-input-number
            v-model="form.price"
            :precision="2"
            :step="0.1"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number
            v-model="form.stock"
            :min="0"
            :precision="0"
          />
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
            active-text="上架"
            inactive-text="下架"
          />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getSeckillProductList,
  addSeckillProduct,
  updateSeckillProduct,
  deleteSeckillProduct,
  uploadSeckillProductImage,
  updateSeckillProductStatus
} from '@/api/seckillProduct'

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 表单对话框
const dialogVisible = ref(false)
const isAdd = ref(true)
const formRef = ref(null)
const form = reactive({
  id: null,
  name: '',
  description: '',
  image: '',
  originalPrice: 0,
  price: 0,
  stock: 0,
  status: 1
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入商品描述', trigger: 'blur' }],
  originalPrice: [{ required: true, message: '请输入原价', trigger: 'blur' }],
  price: [{ required: true, message: '请输入秒杀价', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存', trigger: 'blur' }]
}

// 获取秒杀商品列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getSeckillProductList()
    console.log('获取到的原始数据:', res)
    // 直接使用返回的数组数据
    tableData.value = res
    console.log('表格数据:', tableData.value)
  } catch (error) {
    console.error('获取秒杀商品列表失败:', error)
    ElMessage.error('获取秒杀商品列表失败')
  } finally {
    loading.value = false
  }
}

// 新增商品
const handleAdd = () => {
  isAdd.value = true
  dialogVisible.value = true
  Object.assign(form, {
    id: null,
    name: '',
    description: '',
    image: '',
    originalPrice: 0,
    price: 0,
    stock: 0,
    status: 1
  })
}

// 编辑商品
const handleEdit = (row) => {
  isAdd.value = false
  dialogVisible.value = true
  // 确保ID被正确赋值
  form.id = row.id
  Object.assign(form, {
    name: row.name,
    description: row.description,
    image: row.image,
    originalPrice: row.originalPrice,
    price: row.price,
    stock: row.stock,
    status: row.status
  })
}

// 删除商品
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该秒杀商品吗？', '提示', {
    type: 'warning'
  })
    .then(async () => {
      try {
        await deleteSeckillProduct(row.id)
        ElMessage.success('删除成功')
        getList()
      } catch (error) {
        console.error('删除秒杀商品失败:', error)
        ElMessage.error('删除秒杀商品失败')
      }
    })
    .catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 构建提交数据，确保ID字段存在
        const submitData = {
          id: form.id,
          name: form.name,
          description: form.description,
          image: form.image,
          originalPrice: form.originalPrice,
          price: form.price,
          stock: form.stock,
          status: form.status
        }
        
        const api = isAdd.value ? addSeckillProduct : updateSeckillProduct
        await api(submitData)
        ElMessage.success(isAdd.value ? '新增成功' : '更新成功')
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error(isAdd.value ? '新增秒杀商品失败:' : '更新秒杀商品失败:', error)
        ElMessage.error(isAdd.value ? '新增秒杀商品失败' : '更新秒杀商品失败')
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 图片上传相关方法
const handleImageUpload = async (options) => {
  try {
    const res = await uploadSeckillProductImage(options.file, form.id)
    if (res.code === 1 && res.data && res.data.length > 0) {
      form.image = res.data[0] // 获取第一张图片的URL
      ElMessage.success('上传成功')
    } else {
      ElMessage.error('上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

const beforeImageUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJpgOrPng) {
    ElMessage.error('图片只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 添加状态切换方法
const handleStatusChange = async (row) => {
  try {
    await updateSeckillProductStatus(row.id)
    ElMessage.success(row.status === 1 ? '下架成功' : '上架成功')
    getList() // 刷新列表
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
  }
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.seckill-product-management {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
}

.operation-bar {
  margin-bottom: 20px;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 4px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}
</style> 